//
//  HomeViewCtr.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/4/13.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJExtension
import SDWebImage
import MJRefresh

class HomeViewCtr: BaseViewCtr {
    
    lazy var tableView: UITableView = {
        let tb = UITableView()
        tb.delegate = self
        tb.dataSource = self
        tb.tableFooterView = UIView.init();
        tb.register(UINib.init(nibName: "cell", bundle: nil), forCellReuseIdentifier: "forwardCell")
        tb.register(UINib.init(nibName: "homeCell", bundle: nil), forCellReuseIdentifier: "homeCell")
        tb.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.loadData()
        })
        tb.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {
            self.loadData()
        })
        tb.mj_footer?.isHidden = true
        return tb
    }()
    
    /// 保存所有微博数据
    var statusListModel: StatusListModel = StatusListModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //判断用户登录
        if !isLogin {
            visitorView?.setupVisitorInfo(imageName: nil, title: "关注一些人，回这里看看有什么惊喜")
        }else{
            addView()
            // 4.获取微博数据
            loadData()
        }
        
        setupNav()
        
        NotificationCenter.default.addObserver(self, selector: #selector(titleChage), name: NSNotification.Name(rawValue: ZXJPersentationManagerDidPresented), object: persentationManager)
        NotificationCenter.default.addObserver(self, selector: #selector(titleChage), name: NSNotification.Name(rawValue: ZXJPersentationManagerDidDismissed), object: persentationManager)
        NotificationCenter.default.addObserver(self, selector: #selector(showBrowser), name: NSNotification.Name(rawValue: ZXJShowPhotoBrowserController), object: nil)

        
        
        tableView.estimatedRowHeight = 400
        tableView.separatorStyle = .none
        
        
        // Do any additional setup after loading the view.
    }
    deinit{
        // 移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    static let filePath: String = "loadStatuses.plist".cachesDir()
    
    // MARK: - 内部控制方法
    private func loadData()
    {
        statusListModel.loadData(lastStatus: lastStatus) { (models, error) in
            if error != nil
            {
                SVProgressHUD.setDefaultMaskType(.black)
                SVProgressHUD.showError(withStatus: "获取微博数据失败")
                return
            }
            
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_footer?.isHidden = false

            self.tableView.reloadData()
        }
    }
    
    private func addView(){
        view.addSubview(tableView)
        tableView.mas_makeConstraints { (make) in
            make?.edges.equalTo()(view)
        }
    }
    
    private func setupNav(){
//        let rightBtn = UIButton()
//        rightBtn.setImage(UIImage(named: "navigationbar_pop"), for: .normal)
//        rightBtn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
//        rightBtn.sizeToFit()
//        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        navigationItem.titleView = titleBtn
    }
    
    @objc private func showBrowser(notice: NSNotification){
//        NSLog(message: notice.userInfo)
        guard let pictures = notice.userInfo!["bmiddle_pic"] as? [URL] else {
            SVProgressHUD.setDefaultMaskType(.black
            )
            SVProgressHUD.showError(withStatus: "没有图片")
            return
        }
        
        guard let index = notice.userInfo!["indexPath"] as? IndexPath else {
            SVProgressHUD.setDefaultMaskType(.black
            )
            SVProgressHUD.showError(withStatus: "没有索引")
            return
        }
        let vc = BrowserViewCtr(bmiddle_pic: pictures, indexPath: index)
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true, completion: nil)
    }
    
    @objc private func titleChage(){
        titleBtn.isSelected = !titleBtn.isSelected
    }
    
    @objc private func rightBtnClick(){
        
    }
    
    @objc private func titleBtnClick(btn: UIButton){
//        btn.isSelected = !btn.isSelected;
        
        let sb = UIStoryboard(name: "Popover", bundle: nil)
        guard let menuView = sb.instantiateInitialViewController() else{
            
            return
        }
        menuView.transitioningDelegate = persentationManager
        menuView.modalPresentationStyle = UIModalPresentationStyle.custom
        
        present(menuView, animated: true, completion: nil)
    }

    private lazy var persentationManager: ZXJPersentationManager = {
        let manager = ZXJPersentationManager()
        manager.presentFrame = CGRect(x: 0, y: 45, width: UIScreen.main.bounds.width, height: 300)
        return manager
    }()
    
    //添加标题按钮
    private lazy var titleBtn: TitleButton = {
          let btn = TitleButton()
          btn.setTitle("关注", for: .normal)
          btn.addTarget(self, action: #selector(titleBtnClick), for: .touchUpInside)
        return btn
    }()
    
    ///缓存行高
    private var rowHeightCaches = [String: CGFloat]()
    
    private var lastStatus = false
}

// MARK: - 内部控制方法
extension HomeViewCtr: UITableViewDelegate, UITableViewDataSource
{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListModel.statuses?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewModel = statusListModel.statuses![indexPath.row]
        let indentifier = (viewModel.status.retweeted_status != nil) ? "forwardCell":"homeCell"
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: indentifier, for: indexPath) as! HomeTableViewCell
        // 2.设置数据
        cell.viewModel = viewModel
        // 3.返回cell
        
        if indexPath.row == (statusListModel.statuses!.count - 1 ){
            lastStatus = true
        }else{
            lastStatus = false
        }
        
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

//        let cell = tableView.dequeueReusableCell(withIdentifier: "homeCell") as! HomeTableViewCell
        
        let viewModel = statusListModel.statuses![indexPath.row]
        let indentifier = (viewModel.status.retweeted_status != nil) ? "forwardCell":"homeCell"

        
        guard let height = rowHeightCaches[viewModel.status.idstr ?? "-1"] else{
            NSLog(message: "计算行高")
            let cell = tableView.dequeueReusableCell(withIdentifier: indentifier) as! HomeTableViewCell
            let temp = cell.calculateRowHeight(viewModel: viewModel)
            rowHeightCaches[viewModel.status.idstr ?? "-1"] = temp
            return temp
        }
        
        return height
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        rowHeightCaches.removeAll()
    }
}
